import axios from 'axios'
import store from '@/store'
import { Message } from 'element-ui'

import loading from './loading'

// create an axios instance
const service = axios.create({
  baseURL: '/',
  // baseURL: process.env.BASE_API,
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // loading
    loading.show()

    config.headers['Authorization'] = store.state.user.token // token
    config.headers['Halo-App'] = 'board'
    return config
  },
  error => {
    // Do something with request error
    console.error(error) // for debug
    Promise.reject(error)
  }
)

// respone interceptor
service.interceptors.response.use(
  response => {
    // 此处可以根据状态吗可以做一些逻辑处理
    loading.hide()
    const { data } = response
    if (!data.success && !data.iRet) {
      const info = data.error || data.info
      if (info) {
        Message({
          message: info,
          type: 'error'
        })
      }
      throw new Error(info)
    } else {
      return response.data
    }
  },
  error => {
    console.error(`err${error}`) // for debug
    const { data } = error.response
    if (data.info) error.message = data.info
    loading.hide()
    Message({
      message: error.message,
      type: 'error'
    })
    return Promise.reject(error)
  }
)

export default service
